% Used to post process the output file from SinkToFile class in C++
classdef SinkToFile
    properties
        repeat = 0;
        time = [];
        mean = [];
        var = [];
        VariableName = '';
        VariableUnit = '';
        TimeUnit = 's';
    end
    
    methods
        function record = SinkToFile(filename,repeat)
            if nargin >0
                fid = fopen(filename);
                if(fid<0)% open failed
                    error('Failed to open %s\n',filename);
                end
                formatstring = '%f %f %f';
                data = textscan(fid,formatstring);
                record.time = data{1};
                record.mean = data{2};
                record.var  = data{3};            
                record.repeat = repeat;
                fclose(fid);
            end
            
            if nargin == 2
            end
        end
        
        function h = plot(record,varargin)
            if nargin == 1
               varargin = {'linewidth',2};
            end
            h = plot(record.time,record.mean,varargin{:});
            set(gca,'FontSize',18);
            xlabel('time (s)');
            
            if isempty(record.VariableUnit)
                ylabel(sprintf('%s',record.VariableName));
            else
                ylabel(sprintf('%s (%s)',record.VariableName,record.VariableUnit));
            end
        end   
        
        function record3 = merge(record1,record2)
            % merge the simulation results of multiple runs
            record3 = SinkToFile();
            assert(all(record1.time==record2.time),'Cannot merge to records for different time');
            r1 = record1.repeat;
            r2 = record2.repeat;
            record3.time = record1.time;
            record3.mean = (record1.mean*r1+record2.mean*r2)/(r1+r2);
            record3.var = ((record1.var+record1.mean.^2)*r1+(record2.var+record2.mean.^2)*r2)/(r1+r2)-(record3.mean).^2;
            record3.repeat = record1.repeat+record2.repeat;
        end
        
        function save(record,filename)
            % save to file
            fid = fopen(filename,'w');
            time = record.time;
            mean = record.mean;
            var = record.var;
            for i=1:length(time)
                fprintf(fid,'%15.3f%15.6e%15.6e\n',time(i),mean(i),var(i));
            end
        end
    end
    
    
end

